package com.yl.zqy.service.impl.sys;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yl.zqy.entity.sys.SysRoleUser;
import com.yl.zqy.mapper.sys.SysRoleUserMapper;
import com.yl.zqy.service.sys.SysRoleUserService;
import com.yl.zqy.vo.user.AuthUsersByRole;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色用户关系 服务实现类
 * </p>
 *
 * @author liang.yu
 * @since 2024-03-28
 */
@Service
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserService {

    @Override
    public Long judgeRoleByUserCount(String roleId) {
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getRoleId, roleId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    @Transactional
    public Boolean roleAuthorizeUsers(AuthUsersByRole auth) {
        LambdaQueryWrapper<SysRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleUser::getRoleId, auth.getRoleId());
        baseMapper.delete(queryWrapper);
        List<SysRoleUser> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(auth.getUserId())) {
            auth.getUserId().stream().forEach(item -> {
                SysRoleUser entity = new SysRoleUser();
                entity.setUserId(item);
                entity.setRoleId(auth.getRoleId());
                entity.setCreator(StpUtil.getLoginIdAsString());
                entity.setCreateDate(LocalDateTime.now());
                list.add(entity);
            });
            return saveBatch(list);
        }
        return true;
    }
}
